package com.dyb.nio.future;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class JavaFuture {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        JavaFuture future = new JavaFuture();
        future.run();
    }

    /**
     * callable与runnable接口区别
     * callable可以获取线程执行后的返回值
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public void run () throws ExecutionException, InterruptedException {
        Callable<Boolean> callable = new Task();
        FutureTask<Boolean> futureTask = new FutureTask<>(callable);
        Thread thread = new Thread(futureTask, "线程1");
        thread.start();
        System.out.println(Thread.currentThread().getName() + "\t获取task返回结果");
        Boolean result = futureTask.get();
        System.out.println(Thread.currentThread().getName() + "\t任务返回 " + result);

    }


    class Task implements Callable<Boolean> {

        @Override
        public Boolean call() throws Exception {
            System.out.println(Thread.currentThread().getName() + "\t开始执行任务");
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + "\t结束执行任务");
            return true;
        }
    }

}
